#!/usr/bin/python
# -*- coding: utf-8 -*-
import memcache, sys
from time import sleep
from dbfuncs import MyDBQuery
from tmradiofuncs import loadPage, shortenUrl

MEMCACHE_RECENT_NEWS_KEY = "recentEchoNewsId"
def get_mc_object():
    try:
        mc = memcache.Client(['127.0.0.1:11211'], debug=1)
        if not mc:
            print "Memcached connection error!"
            return None
        else:
            #print "Memcached connection established successfully..."
            return mc
    except Exception as e:
        print "getMemcache error:", e
        return None

def get_from_mc(key, mc = None):
    try:
        if not mc: mc = get_mc_object()
        if mc: 
            result = mc.get(key)
            #print "get_from_mc: {0} = {1}".format(key, result)
        else: 
            print "get_from_mc fail: no memcache object..."
            return None
    except Exception as e:
        print "get_from_mc error:", e
    return result

def set_mc_value(key, value, mc = None):
    try:
        if not mc: mc = get_mc_object()
        if not mc:
            print "set_mc_value fail: no memcache object..."
            return None
    except Exception as e:
        print "set_mc_value error:", e
    mc.set(key, value)
    return True

def get_recent_news_id():
    return get_from_mc(MEMCACHE_RECENT_NEWS_KEY)

def set_recent_news_id(news_id):
    set_mc_value(MEMCACHE_RECENT_NEWS_KEY, news_id)

def get_regular_news_count(recent_id = None):
    print "Fetching regular news count"
    try:
        if not recent_id: recent_id = get_recent_news_id() or 1
        print "Recent news id is {0}".format(recent_id)
        query = """
                    SELECT COUNT(*) AS newsCount
                    FROM echonews.echonews
                    WHERE `id`>{0} AND `date`>=CURRENT_DATE
                """.format(recent_id)
        query_r = MyDBQuery(query)
        if not query_r or len(query_r) == 0: return None
        count = query_r[0]['newsCount']
        print "Regular news count: {0}".format(count)
    except Exception as e:
        print "get_regular_news_count error:", e
    
def get_regular_news(recent_id = None):
    print "Fetching regular news from DB"
    try:
        if not recent_id: recent_id = get_recent_news_id() or 1
        print "Recent news id is {0}".format(recent_id)
        query = """
                    SELECT `id`, `echo_num`, `echo_url`, `date`, `dateStr`, `text`, `path`, `active`
                    FROM echonews.echonews
                    WHERE `id`>{0} AND `date`>=CURRENT_DATE
                    ORDER BY `date` ASC LIMIT 1
                """.format(recent_id)
        query_r = MyDBQuery(query)
        if not query_r or len(query_r) == 0: return None

        news = query_r[0]
        news_string = ""
        if news:
            print "Formatting text..."
            news_string+=news['text'].split(".")[0]+". "
            print "Shortening url..."
            news_string+=shortenUrl(news['echo_url'])+"\n"
        print "Remember recent news id {0}...".format(news['id'])
        set_recent_news_id(news['id'])
        return news_string
    except Exception as e:
        print "get_regular_news error:", e
    return None

def send_news_to_chat(news_string):
    if news_string:
        tries = 0
        while not tries>3:
            try:
                f = open("/home/ekis/tornado/messagefile.txt",'a')
                f.write( news_string.encode('utf-8') )
                f.close()
                return True
            except Exception as e:
                print "send_news_to_chat error:", e
                tries += 1
                sleep(2)
        
    return False

if __name__ == '__main__':
    args = sys.argv
    lastId = None
    getCount = False
    if len(args) > 1:
        for arg in args[1:]:
            if '--help' in arg:
                usageMsg = """Usage: chatechonews.py [--help | --count] [--setid=echoNewsId]
                --help              this message
                --count             prints number of fresh news since last id
                --setid=echoNewsId  set last news id to echoNewsId
                """
                sys.exit(usageMsg)
            if '--count' in arg:
                getCount = True
            if '--setid=' in arg:
                lastId = arg.replace('--setid=', '')
    if getCount:
        print get_regular_newsCount(lastId)
        sys.exit(0)

    news_string = get_regular_news(lastId)
    if news_string: send_news_to_chat(news_string)
